package com.cote.douhahou.pretloan.status;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;

import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.cote.douhahou.pretloan.network.HttpHelper;
import com.cote.douhahou.pretloan.service.CusServiceAkomapalendDialog;
import com.cote.douhahou.pretloan.beans.AppAkomapalendConfigCustomize;
import com.cote.douhahou.pretloan.beans.BaAkomapalendnkAccount;
import com.cote.douhahou.pretloan.beans.LoanApDAkomapalendetailInfo;
import com.cote.douhahou.pretloan.beans.OtheAkomapalendrsInfo;
import com.cote.douhahou.pretloan.beans.ProcessInAkomapalendfo;
import com.cote.douhahou.pretloan.beans.RateAc_akomapalendtiveWind_akomapalendowConfig;
import com.cote.douhahou.pretloan.beans.RateNormalWAkomapalendindowConfig;
import com.cote.douhahou.pretloan.beans.RecommendAkomapalendAppInfo;
import com.cote.douhahou.pretloan.home.HomeActivity;
import com.cote.douhahou.pretloan.msg.AccAkomapalendountList;
import com.cote.douhahou.pretloan.msg.BinAkomapalenddAccoChannelDialog;
import com.cote.douhahou.pretloan.msg.BindAccountAkomapalendDialog;
import com.cote.douhahou.pretloan.msg.DeleteAccountDiAkomapalendalog;
import com.cote.douhahou.pretloan.utils.AkomapaLendUtil;
import com.cote.douhahou.pretloan.R;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

public class LoanStaAkomapalendteWaitFragment extends BaseAkomapalendLnFragment {

    private View stateTopBgView;
    private ImageView stateImgIv;
    private TextView stateTv;
    private View refreshIb;
    private TextView loanAmountTv,loanTermTv;
    private TextView frAccountTitleTv;
    private LinearLayout accountGroupLayout;
    private View frAddAccountBtn;
    private View recommendView;
    private LinearLayout recommendGroupLayout;

    private View tipsView;

    private TextView tipsTitleTv,tipsContentTv;

    private String bindChannelMobile_akomapalend = "";

    private static String page_akomapalend = "";

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_wait, container, false);

        //客服按键
        view.findViewById(R.id.flswa_ib_customerservice).setOnClickListener(v -> new CusServiceAkomapalendDialog(requireContext()).show());

        //两个刷新控件
        refreshIb = view.findViewById(R.id.flswa_ib_refresh);
        refreshIb.setOnClickListener(v -> {
            HttpHelper.inst().submitEvent(page_akomapalend,"REFRESH_CLICK","");
            HttpHelper.inst().process(requireActivity(),() -> {
                String state = ProcessInAkomapalendfo.instance().getAkomapaLendUtil();
                if (AkomapaLendUtil.stateIsChange(state)) {//刷新用户状态
                    FragmentActivity activity = requireActivity();
                    AkomapaLendUtil.clearState();
                    activity.startActivity(new Intent(activity, HomeActivity.class));
                    activity.finish();
                }else HttpHelper.inst().applyDetails(requireActivity(),() -> HttpHelper.inst().fetchAppConfig(requireActivity(),this::refresh_akomapalend));
            });
        });

        SwipeRefreshLayout refreshLayout = view.findViewById(R.id.flswa_refreshlayout);
        refreshLayout.setOnRefreshListener(() -> {
            refreshLayout.setRefreshing(false);
            HttpHelper.inst().submitEvent(page_akomapalend,"REFRESH_CLICK","");
            HttpHelper.inst().process(requireActivity(),() -> {
                String state = ProcessInAkomapalendfo.instance().getAkomapaLendUtil();
                if (AkomapaLendUtil.stateIsChange(state)) {//刷新用户状态
                    FragmentActivity activity = requireActivity();
                    AkomapaLendUtil.clearState();
                    activity.startActivity(new Intent(activity, HomeActivity.class));
                    activity.finish();
                }else HttpHelper.inst().applyDetails(requireActivity(),() -> HttpHelper.inst().fetchAppConfig(requireActivity(),this::refresh_akomapalend));
            });
        });

        stateTopBgView = view.findViewById(R.id.flswa_view_state_topbg);
        stateImgIv = view.findViewById(R.id.flswa_iv_state_img);
        stateTv = view.findViewById(R.id.flswa_tv_state);
        loanAmountTv = view.findViewById(R.id.flswa_tv_loan_amount);
        loanTermTv = view.findViewById(R.id.flswa_tv_loan_term);
        frAccountTitleTv = view.findViewById(R.id.flswa_tv_account_title_fr);
        accountGroupLayout = view.findViewById(R.id.flswa_layout_account_group);
        frAddAccountBtn = view.findViewById(R.id.flswa_btn_add_account_fr);
        recommendView = view.findViewById(R.id.flswa_view_recommend);
        recommendGroupLayout = view.findViewById(R.id.flswa_layout_recommend_group);

        tipsView = view.findViewById(R.id.flswa_view_tips);
        tipsTitleTv = view.findViewById(R.id.flswa_tv_tips_title);
        tipsContentTv = view.findViewById(R.id.flswa_tv_tips_content);

        init_akomapalend();

        return view;
    }

    private void init_akomapalend(){
        //状态:审核通过放款中
        if (ProcessInAkomapalendfo.instance().isOrderLoaning_akomapalend()){
            page_akomapalend = "LOANING";
            stateTopBgView.setBackgroundResource(R.drawable.back_layer_list_gradient);
            stateImgIv.setBackgroundResource(R.drawable.image_bell);
            stateTv.setText(getString(R.string.loan_wait_status_loaning));
            stateTv.setTextColor(Color.parseColor("#FFFF8717"));
            refreshIb.setVisibility(View.GONE);
        }

        //状态:审核中
        else {
            page_akomapalend = "REVIEW";
            stateTopBgView.setBackgroundResource(R.drawable.back_layer_list_2);
            stateImgIv.setBackgroundResource(R.drawable.image_hourglass_2);
            stateTv.setText(getString(R.string.loan_wait_status_review));
            stateTv.setTextColor(Color.parseColor("#FF703EF3"));
            refreshIb.setVisibility(View.VISIBLE);
        }


        //法语区
        if (AkomapaLendUtil.isTsBindAccount()){
            frAccountTitleTv.setVisibility(View.VISIBLE);
            frAddAccountBtn.setVisibility(View.VISIBLE);
        }

        //非法语区
        else {
            frAccountTitleTv.setVisibility(View.GONE);
            frAddAccountBtn.setVisibility(View.GONE);
        }

        //提示文案
        if (AppAkomapalendConfigCustomize.instance().isShowWaitTips()){
            tipsView.setVisibility(View.VISIBLE);
            String title = AppAkomapalendConfigCustomize.instance().getWaitTipsTitle();
            String content = AppAkomapalendConfigCustomize.instance().getWaitTipsText();
            if (!TextUtils.isEmpty(title)) tipsTitleTv.setText(title);
            tipsContentTv.setText(content);
        }else tipsView.setVisibility(View.GONE);

    }

    @Override
    public void onResume() {
        super.onResume();
        HttpHelper.inst().submitEvent(page_akomapalend,"START","");
        HttpHelper.inst().applyDetails(requireActivity(),() ->
                HttpHelper.inst().fetchAppConfig(requireActivity(),this::refresh_akomapalend)
        );
    }

    //更新额度、日期、推荐app显示
    @SuppressLint("SetTextI18n")
    public void refresh_akomapalend(){
        String currency = LoanApDAkomapalendetailInfo.instance().getCurrency_akomapalend();

        loanAmountTv.setText(LoanApDAkomapalendetailInfo.instance().getAmount_akomapalend()+" "+currency);
        loanTermTv.setText(LoanApDAkomapalendetailInfo.instance().getTermStr_akomapalend(requireContext()));

        //app推荐显示
        refreshRecommendAppList_akomapalend();

        //放款账户显示
        refreshAccounts_akomapalend();

    }

    //更新推荐App显示
    public void refreshRecommendAppList_akomapalend(){
        if (!AppAkomapalendConfigCustomize.instance().getRecommendFlag_akomapalend()) {
            recommendView.setVisibility(View.GONE);
            return;
        }
        recommendView.setVisibility(View.VISIBLE);
        recommendGroupLayout.removeAllViews();
        ArrayList<RecommendAkomapalendAppInfo> recommendAppInfos = AppAkomapalendConfigCustomize.instance().getRecommendAppList_akomapalend();
        for (RecommendAkomapalendAppInfo recommendAppInfo:recommendAppInfos){
            addRecommendApp_akomapalend(recommendAppInfo);
            Log.w("---aaaaa----", "refreshRecommendAppList_akomapalend: " );
        }
    }

    //添加推荐App
    private void addRecommendApp_akomapalend(RecommendAkomapalendAppInfo recommendAppInfo){
        View itemView = LayoutInflater.from(requireContext()).inflate(R.layout.item_recommend,null);

        ImageView appLogoIv = itemView.findViewById(R.id.iraa_iv_app_logo);
        TextView appNameTv = itemView.findViewById(R.id.iraa_tv_app_name);
        TextView appAmountTv = itemView.findViewById(R.id.iraa_tv_app_amount);
        TextView appRateTv = itemView.findViewById(R.id.iraa_tv_app_rate);
        TextView appDownloadTv = itemView.findViewById(R.id.iraa_tv_app_download);
        View installBtn = itemView.findViewById(R.id.iraa_btn_install);

        appNameTv.setText(recommendAppInfo.getAp_akomapalendpName());
        appAmountTv.setText(recommendAppInfo.getAmou_akomapalendntText());
        appRateTv.setText(recommendAppInfo.getSc_akomapalendore());
        appDownloadTv.setText(recommendAppInfo.getDow_akomapalendnloads());

        //Install按键
        installBtn.setOnClickListener(v -> {
            HttpHelper.inst().submitEvent(page_akomapalend,"RECOMMEND_"+recommendAppInfo.getAp_akomapalendpName().toUpperCase()+"_INSTALL_CLICK","");
            String path = recommendAppInfo.getP_akomapalendath();
            if (!TextUtils.isEmpty(path))
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(path)));
        });

        //加载logo
        if (recommendAppInfo.getLogo_akomapalendBitmap()==null){
            new Thread(() -> {
                try {
                    String logoPath = recommendAppInfo.getL_akomapalendogo();
                    if (TextUtils.isEmpty(logoPath)) return;
                    URL url = new URL(logoPath);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setConnectTimeout(5000);
                    connection.setRequestMethod("GET");
                    if (connection.getResponseCode()==200){
                        InputStream inputStream = connection.getInputStream();
                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                        recommendAppInfo.setLo_akomapalendgoB_akomapalenditmap(bitmap);
                        new Handler(Looper.getMainLooper()).post(() -> appLogoIv.setImageBitmap(bitmap));
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        }else appLogoIv.setImageBitmap(recommendAppInfo.getLogo_akomapalendBitmap());

        recommendGroupLayout.addView(itemView);
    }

    //放款账户显示
    private void refreshAccounts_akomapalend(){

        accountGroupLayout.removeAllViews();

        if (AkomapaLendUtil.isGh()){//加纳

            View accountView = LayoutInflater.from(requireContext()).inflate(R.layout.item_account_show,null);
            TextView accountTv = accountView.findViewById(R.id.iasa_tv_account);
            accountTv.setText(LoanApDAkomapalendetailInfo.instance().getWltMobile_Gh_akomapalend());
            accountGroupLayout.addView(accountView);
            afterFinishInit_akomapalend();

        }else if (AkomapaLendUtil.isTsBindAccount()){//法语区

            frAddAccountBtn.setOnClickListener(v -> {
                HttpHelper.inst().submitEvent(page_akomapalend,"ADD_CLICK","");
                new BindAccountAkomapalendDialog(requireActivity(), page_akomapalend,
                        mobile -> {
                            bindChannelMobile_akomapalend = mobile;
                            HttpHelper.inst().fAccountList(requireActivity(),this::refreshAccountList_Fr_akomapalend);
                        }
                ).show();
            });

            HttpHelper.inst().fAccountList(requireActivity(),this::refreshAccountList_Fr_akomapalend);

        }else {//其他国家

            View accountView = LayoutInflater.from(requireContext()).inflate(R.layout.item_account_show,null);
            TextView accountTv = accountView.findViewById(R.id.iasa_tv_account);
            accountTv.setText(LoanApDAkomapalendetailInfo.instance().getBkAccount_NiUgKe_akomapalend());
            accountGroupLayout.addView(accountView);
            afterFinishInit_akomapalend();

        }
    }

    //更新法语区绑卡列表
    public void refreshAccountList_Fr_akomapalend(){
        accountGroupLayout.removeAllViews();

        for (BaAkomapalendnkAccount account: AccAkomapalendountList.instance().getBankAccountList_akomapalend()){
            addAccount_Fr_akomapalend(account);
        }

        //更新列表后，判断是否需要绑定运营商
        if (!TextUtils.isEmpty(bindChannelMobile_akomapalend) ){
            if (OtheAkomapalendrsInfo.instance().getAddBindFlag_akomapalend()){
                new BinAkomapalenddAccoChannelDialog(requireContext(), bindChannelMobile_akomapalend,
                        null,
                        () -> HttpHelper.inst().newAccount(
                                    requireActivity(),
                                bindChannelMobile_akomapalend,
                                bindChannelMobile_akomapalend,
                                    OtheAkomapalendrsInfo.instance().getChannel_akomapalend(),
                                    () -> HttpHelper.inst().fAccountList(requireActivity(),this::refreshAccountList_Fr_akomapalend),
                                    false
                        )

                ).show();
                bindChannelMobile_akomapalend = "";
            }
        }else afterFinishInit_akomapalend();
    }

    //法语区添加放款卡
    private void addAccount_Fr_akomapalend(BaAkomapalendnkAccount account){
        if (account == null) return;

        String desc = account.getWalletDesc_akomapalend();

        View accountView = View.inflate(requireContext(), R.layout.item_account, null);
        TextView titleTv = accountView.findViewById(R.id.iafa_tv_title);
        ImageView logoIv = accountView.findViewById(R.id.iafa_iv_logo);
        TextView channelTv = accountView.findViewById(R.id.iafa_tv_channel);
        TextView mobileTv = accountView.findViewById(R.id.iafa_tv_mobile);
        ImageButton deleteIb = accountView.findViewById(R.id.iafa_ib_delete_account);

        titleTv.setVisibility(View.GONE);
        mobileTv.setText(account.getWalletMobile_akomapalend());
        channelTv.setText(desc);

        //删除卡
        deleteIb.setOnClickListener(v -> {
            HttpHelper.inst().submitEvent(page_akomapalend,"DELETE_CLICK",account.getWalletMobile_akomapalend());
            new DeleteAccountDiAkomapalendalog(requireActivity(),account, page_akomapalend,
                    () -> HttpHelper.inst().fAccountList(requireActivity(),this::refreshAccountList_Fr_akomapalend)).show();
        });

        accountGroupLayout.addView(accountView);

        
        if (AppAkomapalendConfigCustomize.instance().getChannelLogoByDesc_akomapalend(desc) == null){
            new Thread(() -> {
                try {
                    if (TextUtils.isEmpty(account.getWalletLogo_akomapalend())) return;
                    if (!AppAkomapalendConfigCustomize.instance().hasAccountChannel_akomapalend()) return;
                    URL url = new URL(account.getWalletLogo_akomapalend());
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setConnectTimeout(5000);
                    connection.setRequestMethod("GET");
                    if (connection.getResponseCode()==200){
                        InputStream inputStream = connection.getInputStream();
                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                        AppAkomapalendConfigCustomize.instance().setChannelLogoByDesc_akomapalend(desc,bitmap);
                        new Handler(Looper.getMainLooper()).post(() -> logoIv.setImageBitmap(bitmap));
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        }else logoIv.setImageBitmap(AppAkomapalendConfigCustomize.instance().getChannelLogoByDesc_akomapalend(desc));

    }

    //页面显示结束后获取评分弹窗配置
    private void afterFinishInit_akomapalend(){
        HttpHelper.inst().fRateConfig(requireActivity(),this::onStarWindowConfigResponse_akomapalend);
    }

    //评分弹窗显示流程
    public void onStarWindowConfigResponse_akomapalend(){
        
        //1.活动弹窗
        if (RateAc_akomapalendtiveWind_akomapalendowConfig.instance().isSwitch_akomapalend() &&
                AkomapaLendUtil.rateCount_Active()< RateAc_akomapalendtiveWind_akomapalendowConfig.instance().getNum_akomapalend()){
            new RateAkomapalendActiveDialog((AppCompatActivity) requireActivity()).show();
            return;
        }

        //2.评价弹窗
        if (RateNormalWAkomapalendindowConfig.instance().isSwitch_akomapalend() &&
                AkomapaLendUtil.rateCount()< RateNormalWAkomapalendindowConfig.instance().getNum_akomapalend()){
            new RateNorDialoAkomapalendg((AppCompatActivity) requireActivity()).show();
        }

    }

    @Override
    public void onPause() {
        super.onPause();
        HttpHelper.inst().submitEvent(page_akomapalend,"END","");
    }

}